import serial
import struct
import time

class USBSerialTool:
    def __init__(self, port, open_flag):
        # 初始化串口，波特率为115200，协议为RS232
        self.open_flag = open_flag
        if self.open_flag:
            self.ser = serial.Serial(
                port=port,
                baudrate=115200,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=1,
                rtscts=True )
        pass

    def open(self):
        # 打开串口
        if self.open_flag:
            if not self.ser.is_open:
                self.ser.open()

    def close(self):
        # 关闭串口
        if self.open_flag:
            if self.ser.is_open:
                self.ser.close()

    def send_data(self, data):
        chunk_size = 100  # 每次发送的字节数
        data_len = len(data)
        for i in range(0, data_len, chunk_size):
            if i + chunk_size >= data_len:
                end = data_len
            else:
                end = i + chunk_size
            chunk = data[i:end]
            self.ser.write(chunk)
            self.ser.flush()  # 确保数据发送完成
            time.sleep(0.02)  # 增加10ms的延迟

    def receive_data(self):
        # 接收数据
        time.sleep(1.5)
        if self.ser.in_waiting > 0:
            return self.ser.read(self.ser.in_waiting).decode()
        return None

    def convert_to_ascii(self, data):
        # 将字符串转换为ASCII码序列
        return [ord(char) for char in data]

    def send_print_content(self, content):
        try:
            if self.ser.is_open:
                data_arr = self.hex_to_bytes(content)
                self.send_data(data_arr)
                response = self.receive_data()
                if response:
                    print("----Received:", response)
                else:
                    print("------no response-------")
            else:
                print(f"-----serial closed-------")
        finally:
            # self.close()
            pass

    def int_to_hex(self, value):
        # 将整数转换为十六进制字符串，并去掉前缀 '0x'
        hex_string = hex(value)[2:]
        # 确保长度为偶数
        if len(hex_string) % 2 != 0:
            hex_string = '0' + hex_string
        return hex_string

    def wrap_packet(self, parts:list):
        if len(parts) > 9:
            parts = parts[:9]

        header = "08"
        command = "09"
        id_part = "00"
        footer = "09"
        divider = "0d0a"


        datas = list()
        for item in parts:
            ascii = self.convert_to_ascii(item)
            bytes_datas = [hex(item)[2:] for item in ascii]
            datas.append("".join(bytes_datas))
            datas.append(divider)

        all_data = "".join(datas)
        data_len = int(len(all_data) / 2)
        len_bytes = data_len.to_bytes(4, 'little')
        print(f"-----len_bytes:{len_bytes}")

        data_byte_array = bytearray(len_bytes.hex(), 'utf-8')

        front = list()
        front.append(header)
        front.append(command)
        front.append(id_part)
        front_byte_array = bytearray("".join(front), 'utf-8')

        back = list()
        back.extend(datas)
        back.append(footer)
        back_byte_array = bytearray("".join(back), 'utf-8')
        return front_byte_array + data_byte_array + back_byte_array

    def str_to_hex(self, original_str):
        # 将字符串编码为字节
        byte_data = original_str.encode('utf-8')
        # 转换为16进制
        hex_bytes = byte_data.hex()
        return str(hex_bytes)

    def hex_to_bytes(self, input_string):
        # 将字符串编码为字节数组
        str_len = len(input_string)
        arr_count = int(str_len / 2)
        arr = bytearray()
        for i in range(0, arr_count):
            arr = arr + bytes.fromhex(input_string[2 * i:(2 * i) + 2])
        return arr


def hex_to_bytes(input_string):
    # 将字符串编码为字节数组
    str_len = len(input_string)
    arr_count = int(str_len / 2)
    arr = bytearray()
    for i in range(0, arr_count):
        arr = arr + bytes.fromhex(input_string[2*i:(2*i)+2])
    return arr

# 使用示例
if __name__ == "__main__":
    # 替换为你的串口号，例如 'COM3' 或 '/dev/ttyUSB0'
    port = '/dev/tty.usbserial-14340'
    usb_serial_tool = USBSerialTool(port)
    usb_serial_tool.open()
    # usb_serial_tool.send_print_content()


    data = "0809009a0000002830312944493130383630303038393235373135283137293237303831362831302930313130313833373634283131293235303731360d0a28303129444931303836303030383932353731350d0a283137293237303831360d0a28313029303131303138333736340d0a283131293235303731360d0a323032352d30372d31360d0a323032372d30382d31360d0a303131303138333736340d0a09"
    data1 = "0809000c00000031320d0a41420d0a61620d0a09"
    data2 = "080900330000002830312962283137293237303732362831302961283131293235303832360d0a28303129620d0a283137293237303732360d0a09"
    data3 = "0809006200000028303129444931303836303030383932353731350d0a283137293237303831360d0a28313029303131303138333736340d0a283131293235303731360d0a323032352d30372d31360d0a323032372d30382d31360d0a303131303138333736340d0a09"
    usb_serial_tool.send_print_content(data1)
    # usb_serial_tool.send_print_content(bytearray(data1,'utf-8'))